//
//  IMBaseMessageViewController.m
//  TQY
//
//  Created by 甘世清 on 2024/10/27.
//

#import "IMBaseMessageViewController.h"
#import "LocationViewController.h"

@interface IMBaseMessageViewController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,QInputBarViewDelegate,QInputBarViewDataSource,InputBoardDataSource,InputBoardDelegate,UITableViewDelegate,UITableViewDataSource,QExtendBoardViewDelegate,QEmotionBoardViewDelegate>
@property (nonatomic , strong) UIImageView * bgImage;

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;



@end

@implementation IMBaseMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.zx_navBarBackgroundColor = UIColor.whiteColor;
//    self.zx_navBarBackgroundColorAlpha = 0.2;
//    self.view.backgroundColor = SQColorF1F1F1;
   
    [self.view addSubview:self.bgImage];
    [self.bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
    }];
    [self.view sendSubviewToBack:self.bgImage];
}

- (void)SQ_UIViewForSelfView{
    self.showEmpty = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(TopHeight, 0, FootHeight+60, 0));
    }];
    [self.keyBoardManager addBottomInputBarView:self.putView belowViewController:NO];
    [self.keyBoardManager bindTextView:self.putView.inputTextView];
}
-(void)SQ_reloadMessageCount{
    self.badge.badgeText = [TQYFMDBManager SQ_getMessageCount];
    if ([self.badge.badgeText isEqualToString:@"0"]) {
        self.badge.hidden = YES;
    } else {
        self.badge.hidden = NO;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [[NSNotificationCenter defaultCenter] postNotificationName:SJChangePopMenuIfNeeded object:nil];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [[NSNotificationCenter defaultCenter] postNotificationName:SJShowPopMenuIfNeeded object:nil];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [[NSNotificationCenter defaultCenter] postNotificationName:SJShowPopMenuIfNeeded object:nil];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //用户手动拖动tableview，隐藏所有面板和键盘
    [self.keyBoardManager hideAllBoardView];
}
//添加到array中 + reload和滚到底部。 needClearInputText: 是否需要清空文本框输入的内容
- (void)insertAndScrollToBottom:(IMMessageModel *)contentModel needClearInputText:(BOOL)needClearInputText {
    if (contentModel ==nil) {
        return;
    }
  
    NSIndexPath * index = [NSIndexPath indexPathForRow:self.jsonArray.count-1 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
    //添加到array中
    NSTimeInterval animationDuration = needClearInputText ? [self.putView clearInputTextBySend] : 0;
    [self scrollToBottomAnimated:YES];
}


//滚到底部
-(void)scrollToBottomAnimated:(BOOL)animated{
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if (rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}
#pragma mark - InputBoardDelegate
//整个“输入View”的高度发生变化（整个View包含bar和表情栏或者键盘，但是不包含底部安全区高度）
- (void)keyboardManager:(QKeyboardManager *)keyboardManager onWholeInputViewHeightDidChange:(CGFloat)wholeInputViewHeight reason:(WholeInputViewHeightDidChangeReason)reason {
    WS(weakSelf);
    BOOL alreadyAtBottom = [self SQ_alreadyAtBottom:weakSelf.tableView];
    UIEdgeInsets insets = UIEdgeInsetsZero;
    insets.top = 0;
    insets.bottom = wholeInputViewHeight-60;
    //对应聊天界面，随着底部输入框的frame.y的变化，为了保持tableview一直都在输入条的上方，修改tableview的contentInset
    self.tableView.contentInset = insets;
    self.tableView.scrollIndicatorInsets = insets;
    if (reason == WholeInputViewHeightDidChangeReasonWillAddToSuperView){ //聊天界面，tableView要滚到底部
        dispatch_async(dispatch_get_main_queue(), ^{
        [self scrollToBottomAnimated:NO];
     });
        return;
    }
    if (reason == WholeInputViewHeightDidChangeReasonTextDidSend) {
        //是点击“发送”按钮清空输入框里的多行文字导致的输入栏高度变化
        return;
    }
    if (alreadyAtBottom) {
        //用自己的animations，问题就是会闪屏，尤其是tableview滚在上方时候 闪的越狠；好处是tableview在切换时候很跟手
        [UIView animateWithDuration:keyboardManager.inputBarHeightChangeAnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self scrollToBottomAnimated:NO];
        } completion:nil];
    } else {
        [self scrollToBottomAnimated:YES];
    }
}



 

#pragma mark - QInputBarViewDelegate
//输入框的高度发生了改变（因为输入框里的文字行数变化了），注意这里仅仅是TextView输入框的高度发生了变化的回调；becauseSendText：YES表示是因为调用了clearInputTextBySend去发送文本
- (void)inputBarView:(QInputBarView *)inputBarView inputTextView:(UITextView *)inputTextView heightDidChange:(CGFloat)changeValue becauseSendText:(BOOL)becauseSendText {
    //这里要告知Manager类
    [self.keyBoardManager inputTextViewHeightDidChange:becauseSendText];
}

//点击表情按钮，切换到表情面板
- (void)inputBarView:(QInputBarView *)inputBarView onEmotionButtonClick:(UIButton *)emotionSwitchButton {
    if (emotionSwitchButton.isSelected) {
        [self.keyBoardManager switchToEmotionBoardKeyboard];
    } else {
        [self.putView textViewBecomeFirstResponder];
    }
}

 
//@return 点表情按钮弹出的表情面板View的高度
- (CGFloat)keyboardManagerEmotionBoardHeight:(QKeyboardManager *)keyboardManager {
    return 274;
}
//@return 点表情按钮弹出的表情面板View，且无需设置frame
- (UIView *)keyboardManagerEmotionBoardView:(QKeyboardManager *)keyboardManager {
    QEmotionBoardView *emotionView = [[QEmotionBoardView alloc] init];
    emotionView.topLineView.hidden = YES;
    [emotionView.sendButton setTitle:SQNSLocalString(@"发送") forState:UIControlStateNormal];
    emotionView.sendButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    QEmotionHelper *faceManager = [QEmotionHelper sharedEmotionHelper];
    emotionView.emotions = faceManager.emotionArray;
    emotionView.delegate = self;
    emotionView.backgroundColor = UIColor.whiteColor;
    return emotionView;
}
#pragma mark - QEmotionBoardViewDelegate
/**
 *  选中表情时的回调
 *  @param  index   被选中的表情在`emotions`里的索引
 *  @param  emotion 被选中的表情对应的`QMUIEmotion`对象
 */
- (void)emotionView:(QEmotionBoardView *)emotionView didSelectEmotion:(QEmotion *)emotion atIndex:(NSInteger)index {

    QEmotionHelper *faceManager = [QEmotionHelper sharedEmotionHelper];
    //把😊插入到输入栏
    [self.putView insertEmotionAttributedString:[faceManager obtainAttributedStringByImageKey:emotion.displayName font:self.putView.inputTextView.font useCache:NO]];
}
// 删除按钮的点击事件回调
- (void)emotionViewDidSelectDeleteButton:(QEmotionBoardView *)emotionView {
    if (![self.putView deleteEmotion]){
        //根据当前的光标，这次点击删除按钮并没有删除表情，那么就删除文字
        [self.putView.inputTextView deleteBackward];
    }
}
//@return 点加号按钮弹出的拓展面板View的高度
- (CGFloat)keyboardManagerExtendBoardHeight:(QKeyboardManager *)keyboardManager{
    return 174;
}
//@return 点加号按钮弹出的拓展面板View，且无需设置frame
- (UIView *)keyboardManagerExtendBoardView:(QKeyboardManager *)keyboardManager{
    QExtendBoardView *boardView = [[QExtendBoardView alloc] init];
    boardView.delegate = self;
    boardView.backgroundColor = UIColor.whiteColor;
    QExtendBoardItemModel *photoItem = [[QExtendBoardItemModel alloc]initWithNormalIconImage:SQGetImage(@"照片_nomal") title:@"图片"];
    QExtendBoardItemModel *photoItem2 = [[QExtendBoardItemModel alloc]initWithNormalIconImage:SQGetImage(@"拍摄_nomal") title:@"拍照"];
    QExtendBoardItemModel *photoItem3 = [[QExtendBoardItemModel alloc]initWithNormalIconImage:SQGetImage(@"定位_nomal") title:@"位置"];
    boardView.extendBoardItems = @[photoItem2,photoItem,photoItem3];
    return boardView;
}
// 发送按钮的点击事件回调
- (void)emotionViewDidSelectSendButton:(QEmotionBoardView *)emotionView {
    [self inputBarView:self.putView onKeyboardSendClick:[self.putView textViewInputNormalText]];
}
/// 点击+按钮
/// - Parameters:
///   - inputBarView: inputBarView description
///   - extendSwitchButton: extendSwitchButton description
- (void)inputBarView:(QInputBarView *)inputBarView onExtendButtonClick:(UIButton *)extendSwitchButton {
    [self.keyBoardManager switchToExtendBoardKeyboard];
}

#pragma mark - QExtendBoardViewDelegate
//点击拓展面板的cell
- (void)didSelectExtendBoardItem:(QExtendBoardItemModel *)shareMenuItem atIndex:(NSInteger)index {
    WS(weakSelf);
    if (index ==0) {
        [self presentViewController:self.imagePickerVc animated:YES completion:nil];
    } else  if (index ==1) {
        WS(weakSelf);
        TZImagePickerController * vc = [[TZImagePickerController alloc]init];
        vc.maxImagesCount = 9;
        vc.allowPickingVideo = NO;
        vc.allowTakeVideo = NO;
        vc.showPhotoCannotSelectLayer = YES;
        vc.sortAscendingByModificationDate = NO;
        [self presentViewController:vc animated:YES completion:nil];
        [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            [weakSelf SQ_getImages:[NSMutableArray arrayWithArray:photos]];
        }];
    }else{
        LocationViewController * vc = [[LocationViewController alloc]init];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:vc animated:YES completion:nil];
        [vc setAddressBlock:^(NSMutableDictionary * _Nonnull addressDic) {
            [weakSelf SQ_sendLoaction:addressDic];
        }];
    }
}
//相机
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
        if (photo == nil)
            {
                photo = [info objectForKey:UIImagePickerControllerOriginalImage];
            }
        [self SQ_getImages:[NSMutableArray arrayWithObject:photo]];
    }else
    {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"相机数据异常")];
    }
}

-(void)SQ_getImages:(NSMutableArray *)imageArray{
   //生成模型.然后调用
    for (UIImage * image in imageArray) {
        [self SQ_getImage:image];
    }
}
-(void)SQ_getImage:(UIImage *)image{
    
}

-(void)SQ_sendLoaction:(NSMutableDictionary*)dic{
    
}

-(BOOL)SQ_alreadyAtBottom:(UITableView*)view{
    if (((NSInteger)view.contentOffset.y) == ((NSInteger)view.contentSize.height + view.adjustedContentInset.bottom - CGRectGetHeight(view.bounds))) {
        return YES;
    }
    return NO;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [UITableViewCell new];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return  0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (UIImagePickerController *)imagePickerVc{
    if (!_imagePickerVc) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        _imagePickerVc.allowsEditing = NO;
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
            _imagePickerVc.sourceType = sourceType;
        }
    }
    return _imagePickerVc;
}

- (UIImageView *)bgImage{
    if (!_bgImage) {
        _bgImage = [[UIImageView alloc]init];
        _bgImage.contentMode = UIViewContentModeScaleAspectFill;
        _bgImage.clipsToBounds = YES;
        _bgImage.image = SQGetImage(@"IM背景");
    }
    return _bgImage;
}
- (QKeyboardManager *)keyBoardManager{
    if (!_keyBoardManager) {
        _keyBoardManager = [[QKeyboardManager alloc]initWithViewController:self];
        _keyBoardManager.dataSource = self;
        _keyBoardManager.delegate = self;
    }
    return _keyBoardManager;
}
- (QInputBarView *)putView{
    if (!_putView) {
        _putView = [[QInputBarView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 60)];
        _putView.delegate = self;
        _putView.dataSource = self;
        QInputBarViewConfiguration *config = [QInputBarViewConfiguration defaultInputBarViewConfiguration];
        config.inputBarBackgroundColor =  UIColor.whiteColor;
        config.inputBarBoardColor = UIColor.whiteColor;
        config.textViewBackgroundColor = SQColorF1F1F1;
        config.voiceButtonHidden = YES;
        config.textColor = UIColor.blackColor;
        [_putView setupWithConfiguration:config];
    }
    return _putView;
}

- (JSBadgeView *)badge{
    if (!_badge) {
        _badge = [[JSBadgeView alloc]initWithParentView:self.zx_navLeftBtn alignment:JSBadgeViewAlignmentCenterRight];
        _badge .backgroundColor = SQColor(@"#FF3B30");
        _badge.badgePositionAdjustment = CGPointMake(0, 0);
        _badge.badgeTextFont = FONT_REGULAR(12);
        _badge.layer.cornerRadius = 8;
        _badge.layer.masksToBounds = YES;
    }
    return _badge;
}
@end
